import datetime
import orders
import commons
from loguru import logger
from env_config import EnvConfig


def work(clone_name=None):
    if clone_name is None:
        clone_name = f"by3_{EnvConfig.get_clone_name()}"
    commons.MYSQL_DB = clone_name
    orders_helper = orders.OrdersHelper()
    orders_db = orders_helper.get_orders_db()
    orders_bi = orders_helper.get_orders_binance(limit=1000)
    quote_buy = 0
    time_buy = 0
    quote_sell = 0
    for order_id in orders_db:
        try:
            order = orders_bi[order_id]
        except KeyError:
            continue
        utc_time = datetime.datetime.utcfromtimestamp(int(order['time']) / 1000)
        if utc_time.strftime('%Y%m%d') != datetime.date.today().strftime('%Y%m%d'):
            continue
        if order['status'] != 'FILLED':
            continue
        if order['side'] == 'BUY':
            quote_buy += float(order['cummulativeQuoteQty'])
            time_buy += 1
        else:
            quote_sell += float(order['cummulativeQuoteQty'])
    percent = (quote_sell - quote_buy) / quote_buy * 100 if quote_buy > 0 else 0
    percent = round(percent, 4)
    quote_buy = round(quote_buy, 4)
    quote_sell = round(quote_sell, 4)
    logger.debug(
        f"{commons.MYSQL_DB}: 买入次数={time_buy},\t买入={quote_buy},\t卖出={quote_sell},\t盈利率={percent}%")


if __name__ == '__main__':
    # 验证环境配置
    EnvConfig.validate_config()
    
    logger.add(f"/log/log_statistics.txt", rotation="00:00")
    logger.info("_____________________________________________________")
    work("by3_clone_a")
    work("by3_clone_b")
    work("by3_clone_c")
    work("by3_clone_d")
    work("by3_clone_e")
    work("by3_clone_f")
